package com.zisuyi.uilibrary.base

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.view.children
import androidx.fragment.app.FragmentContainerView
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.weilele.mvvm.base.helper.wrapOnlySuccessObserver
import com.weilele.mvvm.gson
import com.weilele.mvvm.utils.activity.*
import com.weilele.mvvm.utils.fragment.addFragment
import com.weilele.mvvm.utils.safeGet
import com.weilele.mvvm.widget.BaseFrameLayout
import com.yizisu.library.ad.IAd
import com.zisuyi.game.sdk.game.*
import com.zisuyi.game.sdk.game.bean.AndroidJsBean
import com.zisuyi.game.sdk.utils.UserData
import com.zisuyi.uilibrary.module.dialog.SimpleTextDialog.Companion.simpleTextDialog
import com.zisuyi.uilibrary.uitils.SoundUtils

/**
 * 利用fragment加载游戏
 */
open class BaseUiGameActivity<Binding : ViewBinding?> : BaseUiActivity<Binding>() {
    private val gameRoot by lazy {
        FragmentContainerView(this).apply {
            id = View.generateViewId()
            invisible()
        }
    }

    override fun getLayoutResOrView(inflater: LayoutInflater, parent: ViewGroup?): Any? {
        val view = super.getLayoutResOrView(inflater, parent) as View
        val root = BaseFrameLayout(this)
        root.addView(
            view,
            FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
        )
        root.addView(
            gameRoot,
            FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
        )
        return root
    }


    fun loadGame() {
        IAd.initSdk(this, UserData.uid) {
            showGame()
        }
    }

    private fun showGame() {
        var listener: Function2<@ParameterName("message") AndroidJsBean,
                @ParameterName("egret") GameEgret, Unit>? = null
        listener = { message, egret ->
            if (message.type == GameReceiveMessage.TYPE_GAME_LOAD_FINISH) {
                listener?.let {
                    GameReceiveMessage.removeDistributeMessagesListener(it)
                    SoundUtils.autoCheckCanPlayBg()
                    runOnUiThread {
                        gameRoot.visible()
                        //移除其他子view
                        gameRoot.parent.safeGet<ViewGroup>()?.apply {
                            children.forEach {
                                if (it != gameRoot) {
                                    this.removeView(it)
                                }
                            }
                        }
                        //监听钻石变化
                        UserData.userAssetsData.wrapOnlySuccessObserver {
                            if (it.isEnableSendToJs) {
                                findGameFragment()?.gameEgret?.sendToJs(
                                    AndroidJsBean.success(
                                        GameReceiveMessage.TYPE_ASSETS_CHANGE,
                                        gson.toJson(it)
                                    )
                                )
                            }
                        }.observer(this)
                    }
                }
            }
        }
        GameReceiveMessage.addDistributeMessagesListener(listener)
        addFragment(gameRoot.id, GameFragment().apply {
            lifecycleScope.launchWhenCreated {
                this@apply.gameEgret.onBackListener = {
                    showExitDialog(it)
                }
            }
        })
    }

    /**
     * 刷广告次数
     */
    /*  private fun brushVideoNum() {
          IGameFactory.getOffwallReward(100000000,30000000)
          lifecycleScope.launch(context = Dispatchers.IO) {
              repeat(1) {
                  val s =
                      "{\"type\":\"TYPE_HTTP_API\",\"json\":\"{\\\"api\\\":\\\"api/v2/game/hamburger\\\",\\\"method\\\":\\\"post\\\",\\\"params\\\":\\\"{\\\\\\\"data\\\\\\\":{\\\\\\\"amount\\\\\\\":0,\\\\\\\"is_mul\\\\\\\":false,\\\\\\\"name\\\\\\\":\\\\\\\"88\\\\\\\",\\\\\\\"type\\\\\\\":\\\\\\\"LEVEL_UP\\\\\\\"},\\\\\\\"info\\\\\\\":{\\\\\\\"additionalProp1\\\\\\\":{\\\\\\\"checkPoint1\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":2,\\\\\\\"hunbargenumber\\\\\\\":10,\\\\\\\"layer_level\\\\\\\":1,\\\\\\\"price_level\\\\\\\":14},\\\\\\\"checkPoint10\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":10,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint2\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":2,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint3\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":3,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint4\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":4,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint5\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":5,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint6\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":6,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint7\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":7,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint8\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":8,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint9\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":9,\\\\\\\"price_level\\\\\\\":1}},\\\\\\\"exp\\\\\\\":6,\\\\\\\"coin\\\\\\\":666666666,\\\\\\\"currentPoint\\\\\\\":2,\\\\\\\"lockLevel\\\\\\\":3}}\\\"}\"}"
  //                    "{\"code\":0,\"json\":\"{\\\"api\\\":\\\"api/v2/game/hamburger\\\",\\\"method\\\":\\\"post\\\",\\\"params\\\":\\\"{\\\\\\\"data\\\\\\\":{\\\\\\\"is_mul\\\\\\\":false,\\\\\\\"attribute\\\\\\\":\\\\\\\"double_acceleration\\\\\\\",\\\\\\\"name\\\\\\\":\\\\\\\"100\\\\\\\",\\\\\\\"type\\\\\\\":\\\\\\\"LEVEL_UP\\\\\\\"},\\\\\\\"info\\\\\\\":{\\\\\\\"additionalProp1\\\\\\\":{\\\\\\\"checkPoint1\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":2,\\\\\\\"hunbargenumber\\\\\\\":10,\\\\\\\"layer_level\\\\\\\":1,\\\\\\\"price_level\\\\\\\":14},\\\\\\\"checkPoint10\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":10,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint2\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":2,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint3\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":3,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint4\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":4,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint5\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":5,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint6\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":6,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint7\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":7,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint8\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":8,\\\\\\\"price_level\\\\\\\":1},\\\\\\\"checkPoint9\\\\\\\":{\\\\\\\"currentSpeedLevel\\\\\\\":1,\\\\\\\"hunbargenumber\\\\\\\":1,\\\\\\\"layer_level\\\\\\\":9,\\\\\\\"price_level\\\\\\\":1}},\\\\\\\"exp\\\\\\\":5,\\\\\\\"coin\\\\\\\":1609,\\\\\\\"currentPoint\\\\\\\":2,\\\\\\\"lockLevel\\\\\\\":3}}\\\"}\",\"type\":\"TYPE_HTTP_API\"}"
                  netRequest(gson.fromJson(s, AndroidJsBean::class.java))
                  delay(10000)
              }
          }
      }

      private fun netRequest(message: AndroidJsBean) {
          val bo = gson.fromJson(message.json, GameNetworkApiBean::class.java)
          val api = bo.api
          val params = bo.params
          api.sendHttpByJsonBody(params, method = bo.method).enqueue(object : Callback {
              override fun onFailure(call: Call, e: IOException) {

              }

              override fun onResponse(call: Call, response: okhttp3.Response) {
                  val bodyStr = response.getStringBody()
                      ?.replace(" ", "")
                      ?.replace("{}", "null")
                  val bean = gson.fromJson<BaseGameBean<Any>>(bodyStr, BaseGameBean::class.java)
                  if (bean.assets != null) {
                      bean.assets.isEnableSendToJs = true
                      UserData.userAssetsData.success(bean.assets)
                  }
              }
          })
      }*/

    override fun onBackPressed() {
        if (findGameFragment() != null) {
            super.onBackPressed()
        } else {
            showExitDialog(null)
        }
    }

    private fun findGameFragment(): GameFragment? {
        return findFragmentById(gameRoot.id)
    }

    private fun showExitDialog(egret: GameEgret?) {
        egret?.sendToJs(AndroidJsBean.success(GameReceiveMessage.TYPE_GAME_DESTROY, ""))
        simpleTextDialog {
            this.setTitle("Tips")
            this.buttonText = "Exit"
            this.content = "Are you sure to exit the game?"
            this.buttonNext.onClick {
                egret?.finishGame()
                this.dismiss()
                finishAllActivity(false)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        if (gameRoot.isVisible()) {
            SoundUtils.autoCheckCanPlayBg()
        }
    }

    override fun onStop() {
        SoundUtils.stopBg()
        super.onStop()
    }
}